import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class ServerGUI extends JFrame {
    private JTextArea logArea;
    private JButton startStopButton;
    private JTextField cacheLimitField;
    private JTextField threadPoolSizeField;
    private JTextField remoteDnsServerField;
    private Server server;

    public ServerGUI() {
        setTitle("DNS Relay Server");
        setSize(600, 400);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLayout(new BorderLayout());

        logArea = new JTextArea();
        add(new JScrollPane(logArea), BorderLayout.CENTER);

        JPanel configPanel = new JPanel();
        configPanel.add(new JLabel("Cache Limit:"));
        cacheLimitField = new JTextField(5);
        cacheLimitField.setText(String.valueOf(Server.cacheLimitInDaysDefault)); // 设置cacheLimitField的默认值为"100"
        configPanel.add(cacheLimitField);

        configPanel.add(new JLabel("Thread Pool Size:"));
        threadPoolSizeField = new JTextField(5);
        threadPoolSizeField.setText(String.valueOf(Server.threadPoolSizeDefault)); // 设置threadPoolSizeField的默认值为"10"
        configPanel.add(threadPoolSizeField);

        configPanel.add(new JLabel("Remote DNS Server:"));
        remoteDnsServerField = new JTextField(10);
        remoteDnsServerField.setText(String.valueOf(Server.remoteDnsServerDefault)); // 设置remoteDnsServerField的默认值为"8.8.8.8"
        configPanel.add(remoteDnsServerField);
        add(configPanel, BorderLayout.NORTH);

        startStopButton = new JButton("Start");
        startStopButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if (server == null) {
                    server = new Server(Integer.parseInt(cacheLimitField.getText()),
                            Integer.parseInt(threadPoolSizeField.getText()),
                            remoteDnsServerField.getText(),
                            new Log() {
                                @Override
                                public void addLog(String log) {
                                    super.addLog(log);
                                    logArea.append(log + "\n");
                                }
                            });
                    new Thread(server).start();
                    startStopButton.setText("Stop");
                } else {
                    server.stop();
                    server = null;
                    startStopButton.setText("Start");
                }
            }
        });
        add(startStopButton, BorderLayout.SOUTH);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new ServerGUI().setVisible(true);
            }
        });
    }
}